﻿using System;
using Volo.Abp.Validation.StringValues;

namespace Xms.Abp.Validation.StringValues;

[Serializable]
[ValueValidator("DATE_TIME")]
public class DateTimeValidator : ValueValidatorBase
{
    public DateTime MinValue
    {
        get => (this["MinValue"] ?? "0").To<DateTime>();
        set => this["MinValue"] = value;
    }

    public DateTime MaxValue
    {
        get => (this["MaxValue"] ?? "0").To<DateTime>();
        set => this["MaxValue"] = value;
    }

    public DateTimeValidator()
    {
        MinValue = DateTime.MinValue;
        MaxValue = DateTime.MaxValue;
    }

    public DateTimeValidator(DateTime? minValue = null, DateTime? maxValue = null)
    {
        MinValue = minValue ?? DateTime.MinValue;
        MaxValue = maxValue ?? DateTime.MaxValue;
    }

    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return false;
        }

        if (value is DateTime dateTime)
        {
            return IsValidInternal(dateTime);
        }

        if (value is string str)
        {
            if (DateTime.TryParse(str, out var dateTimeValue))
            {
                return IsValidInternal(dateTimeValue);
            }
        }

        return false;
    }

    protected virtual bool IsValidInternal(DateTime value)
    {
        return value.IsBetween(MinValue, MaxValue);
    }
}
